/* eslint-disable no-mixed-spaces-and-tabs */
// 压缩图片
export const compressImage = (file, maxWidth = 1200, maxHeight = 800) => {
	return new Promise((resolve, reject) => {
	  const reader = new FileReader();
	  reader.onload = (event) => {
		const img = new Image();
		img.onload = () => {
		  const canvas = document.createElement('canvas');
		  let width = img.width;
		  let height = img.height;
  
		  // 计算缩放比例，保持纵横比
		  if (width > maxWidth || height > maxHeight) {
			const ratio = Math.min(maxWidth / width, maxHeight / height);
			width *= ratio;
			height *= ratio;
		  }
  
		  canvas.width = width;
		  canvas.height = height;
		  const ctx = canvas.getContext('2d');
		  ctx.drawImage(img, 0, 0, width, height);
		  
		  // 将 Canvas 转换为 Blob
		  canvas.toBlob((blob) => {
			// 创建一个新的File对象
			const compressedFile = new File([blob], file.name, {
			  type: file.type,
			  lastModified: Date.now()
			});
			resolve(compressedFile);
		  }, file.type);
		};
		img.onerror = (error) => {
		  console.error('Image loading error:', error);
		  reject(error);
		};
		img.src = event.target.result;
	  };
	  reader.onerror = (error) => {
		console.error('File reading error:', error);
		reject(error);
	  };
  
	  // 如果 file 不是 Blob 对象，则将其转换为 Blob 对象
	  const blob = file instanceof Blob ? file : new Blob([file]);
	  reader.readAsDataURL(blob);
	});
  };
  